package cn.tianyigps.m7.template;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import io.netty.util.internal.StringUtil;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;

import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;


/**
 * Created with IDEA
 *
 * @description: mongo操作模板类
 * @author: cui.guibin
 * @create: 2019/3/27 10:09
 **/
public class MongoTemplate {

    private static MongoDatabase DB = null;
    static {
        // 创建一个mongo的连接池
        Properties prop = new Properties();
        try {
            prop.load(MongoTemplate.class.getClassLoader().getResourceAsStream("mongo.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String host = prop.getProperty("mongo.host");
        int port = new Integer(prop.getProperty("mongo.port"));
        String username = prop.getProperty("mongo.username");
        String password = prop.getProperty("mongo.password");
        String database = prop.getProperty("mongo.db");
        ServerAddress serverAddress = new ServerAddress(host, port);
        MongoClient mongoClient = null;
        if (!StringUtil.isNullOrEmpty(username)) {
            MongoCredential credential = MongoCredential.createCredential(username, database, password.toCharArray());
            mongoClient = new MongoClient(serverAddress, Arrays.asList(credential));
        }else{
            mongoClient = new MongoClient(serverAddress);
        }
        CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()));
        DB = mongoClient.getDatabase(database).withCodecRegistry(pojoCodecRegistry);
    }

    public static MongoCollection getCollection(String collection,Class c){
        return DB.getCollection(collection, c);
//        MongoCollection collection1 = DB.getCollection(collection, c);
    }
    public static MongoCollection getCollection(String collection){
        return DB.getCollection(collection);
    }


}
